local ip = ngx.req.get_headers()["X-Real-IP"];
if ip == nil then
    ip = ngx.var.remote_addr;
end

local userAgent = ngx.req.get_headers()["user-agent"]
 
-- ngx.log(ngx.ERR, ngx.req.get_headers()["user-agent"])
-- ngx.log(ngx.ERR, ip)
package.path = ngx.var.lua_script_dir .. "-production/?.lua;;"
package.cpath = ngx.var.lua_script_dir .. "-production/?.so;;"



local args = ngx.req.get_uri_args()
if userAgent then
	if string.find(userAgent, "http/") or string.find(userAgent, "Darwin/")then
		args.fromApp = true
	end
else
	args.fromApp = true
end
args.ip = ip

local _,_,name = string.find(ngx.var.uri, '^/([^/]+)')
if not name then
    ngx.print("no controller")
    ngx.exit(200)
end
local _,_,action = string.find(ngx.var.uri, '^/[^/]+/([^/]+)')
if action then
    args.action = action
end
if action ~= "analyze" then
	ngx.header.content_type = "application/json"
	ngx.header.charset = "utf-8"
end
if args.v then
	package.path = ngx.var.lua_script_dir .."-"..args.v .. "/?.lua;;"
	package.cpath = ngx.var.lua_script_dir .. "-"..args.v .. "/?.so;;"
end

local ok, controller = pcall(require, string.lower(name))
if not ok then
	ngx.print("invalid controller",name)
    ngx.exit(200)
end
controller.default(args)
